package se.sweco.ws.impl;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TrelocityContentHandler extends DefaultHandler {
	private List<TrafficData> data;
	private List<Route> routes;
	private Route route;
	private short reliability;
	private double time;
	
	private StringBuffer sb;

	public TrelocityContentHandler(List<Route> routes) {
		this.routes = routes;
	}
	public List<TrafficData> getData() {
		return data;
	}

	public void startDocument() {
		data = new ArrayList<TrafficData>();
		route = null;
		sb = new StringBuffer();
	}

	public void startElement(String ns, String localName, String qName, Attributes attr) throws SAXException {
		sb.setLength(0);
		if (localName.equals("route")) {
			route = null;
		}
	}
	
	public void endElement(String namespaceURI, String localName, String qName) {
		if (localName.equals("id")) {
			int routeId = Integer.parseInt(sb.toString().trim());
			for (Route r : routes) {
				if (r.getRouteId() == routeId) {
					route = r;
				}
			}
		} else if (localName.equals("currentTime")) {
			time = Double.parseDouble(sb.toString().trim());
		} else if (localName.equals("accuracy")) {
			reliability = Short.parseShort(sb.toString().trim());
		} else if (localName.equals("route")) {
			for (int i = 1; i < route.getCoords().size(); i++) {
				TrafficData d = new TrafficData();
				d.startCoord = route.getCoords().get(i - 1);
				d.endCoord = route.getCoords().get(i);
				d.reliability = reliability;
				d.time = time / route.getCoords().size(); // avg time over route
				
				data.add(d);
			}
		}
	}
	
	public void characters(char[] buf, int start, int len) {
		sb.append(buf, start, len);
	}
}
